package com.leozhang.app;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class AESCryptoUtil {

    // 16字节密钥（对应 CryptoJS 的 key）
    private static final String KEY = "HfkdIzPG4/eZD0S=";
    // 16字节IV（对应 CryptoJS 的 iv）
    private static final String IV = "TBawpOJlNkb5K+9=";
    private static final String ALGORITHM = "AES";
    private static final String TRANSFORMATION = "AES/CBC/PKCS5Padding";

    // AES加密
    public static String encrypt(String data) throws Exception {
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes("UTF-8"), ALGORITHM);
        IvParameterSpec ivSpec = new IvParameterSpec(IV.getBytes("UTF-8"));

        cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
        byte[] encrypted = cipher.doFinal(data.getBytes("UTF-8"));
        return Base64.getEncoder().encodeToString(encrypted);
    }

    // AES解密
    public static String decrypt(String encryptedData) throws Exception {
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes("UTF-8"), ALGORITHM);
        IvParameterSpec ivSpec = new IvParameterSpec(IV.getBytes("UTF-8"));

        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
        byte[] decodedBytes = Base64.getDecoder().decode(encryptedData);
        byte[] decrypted = cipher.doFinal(decodedBytes);
        return new String(decrypted, "UTF-8");
    }

    // 测试方法
    public static void main(String[] args) {
        try {
            // 用户输入原始密码，加密后传给后端
            String userName = "admin";
            String originalText = "7uzQi@NGFU4";
            String encryptedText = encrypt(originalText);

            // 后端解密
            String decryptedText = decrypt(encryptedText);

            System.out.println("原文: " + originalText);
            System.out.println("加密后: " + encryptedText);
            System.out.println("解密后: " + decryptedText);

            // 后端生成随机的salt，将原始密码再次加密后存入数据库中
            String salt = "379f579929e84ae49989496d40201bd9";
            String signContent = userName.trim() + originalText.trim();
            String passwordInDB = UserUtils.sign(signContent, salt);
            System.out.println("靶场用户存入数据库的密码: " + passwordInDB);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
